<template>
  <nav class="navbar">
    <ul>
      <li v-for="table in tables" :key="table.table_name">
        <router-link :to="`/table/${table.table_name}`">{{ table.label }}</router-link>
      </li>
    </ul>
  </nav>
  <div>
    <div class="operations" style="margin-top: 10px; margin-bottom: 10px; margin-left: 8px">
      <el-button @click="handleAdd">插入行</el-button>
      <el-button @click="deleteSelectedRows">删除行</el-button>
      <el-button @click="openEditDialog">修改行</el-button>
      <el-button style="margin-left: 8px;margin-right: 8px">提交</el-button>
      <div style="margin-top: 10px; margin-bottom: 10px;">
        <el-input :style="{ width: '300px' }" v-model="searchTerm" placeholder="勾选列后输入关键字"></el-input>
        <el-button style="margin-left: 20px;margin-right: 8px" @click="handleSearch">搜索</el-button>
        <el-button @click="toggleColumnSelector">选择列</el-button>
        <div v-if="isColumnSelectorVisible" class="column-selector">
          <el-checkbox-group v-model="selectedColumns">
            <el-checkbox v-for="column in columns" :key="column.name" :label="column.name">
              {{ column.label || column.name }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      <el-button @click="handleReset">
        <el-icon>
          <Refresh />
        </el-icon>
      </el-button>
    </div>

    <el-dialog title="插入新数据" v-model="isAddDialogVisible" width="50%">
      <el-form :model="formData">

        <el-form-item v-for="column in filteredColumns"
                      :key="column.name"
                      :label="column.label || column.name"
        >
          <!-- 对于VARCHAR或TEXT类型 -->
          <template v-if="['varchar', 'text', 'double','float','int'].includes(column.type)">
            <el-input v-model="formData[column.name]"></el-input>
          </template>
          <!-- 对于DATE类型 -->
          <template v-else-if="column.type === 'date'">
            <el-date-picker v-model="formData[column.name]" type="date" placeholder="选择日期"></el-date-picker>
          </template>
          <!-- 对于DATETIME类型 -->
          <template v-else-if="column.type === 'datetime'">
            <el-date-picker v-model="formData[column.name]" type="datetime"
                            placeholder="选择日期和时间"></el-date-picker>
          </template>
          <template v-else-if="column.type === 'blob'">
            <el-upload
              :action="uploadUrl"
              :before-upload="beforeImageUpload"
              :on-success="handleImageSuccess"
              list-type="picture">
              <el-button slot="trigger" size="small" type="primary">选取图片</el-button>
              <el-button size="small" type="success" icon="el-icon-upload2" @click="submitImage">上传</el-button>
              <div slot="tip" class="el-upload__tip">只支持 jpg/png 文件，且不超过500kb</div>
            </el-upload>
          </template>
          <!-- 可以添加其他类型的处理 -->
        </el-form-item>
      </el-form>
      <template #footer>
    <span class="dialog-footer">
      <el-button @click="isAddDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitFormData">确定</el-button>
    </span>
      </template>
    </el-dialog>


    <el-dialog title="修改数据" v-model="isEditDialogVisible" width="50%">
      <el-form :model="editFormData">
        <el-form-item v-for="column in filteredColumns" :key="column.name" :label="column.label || column.name">
          <template v-if="['varchar', 'text', 'double','float','int'].includes(column.type)">
            <el-input v-model="editFormData[column.name]"></el-input>
          </template>
          <template v-else-if="column.type === 'blob'">
            <el-upload
              :action="uploadUrl"
              :before-upload="beforeImageUpload"
              :on-success="handleImageSuccess"
              list-type="picture">
              <el-button slot="trigger" size="small" type="primary">选取图片</el-button>
              <el-button size="small" type="success" icon="el-icon-upload2" @click="submitImage">上传</el-button>
              <div slot="tip" class="el-upload__tip">只支持 jpg/png 文件，且不超过500kb</div>
            </el-upload>
          </template>
        </el-form-item>
      </el-form>
      <template #footer>
    <span class="dialog-footer">
      <el-button @click="isEditDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitEditData">确定</el-button>
    </span>
      </template>
    </el-dialog>

    <div class="table-name">
      <h2 class="table-title">{{ realTableName }}</h2> <!-- 你可能还需要逻辑来根据table_name找到对应的label -->
    </div>

    <el-table :data="tableData"
              @selection-change="handleSelectionChange"
              @row-click="handleRowClick">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column
        v-for="column in uniqueCols"
        :key="column.name"
        :prop="column.name"
        :label="column.label || column.name">
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, toRefs, computed } from "vue";
import { useRoute } from "vue-router";
import axios from "axios";
import { ElMessage } from "element-plus";
import request from "@/utils/request";
import { column } from "element-plus/es/components/table-v2/src/common";

const tableLabels = ref([]);
const uploadUrl = "YOUR_BACKEND_API_URL"; // 你的后端API的URL
const selectedRow = ref(null);
const isEditDialogVisible = ref(false);
const editFormData = reactive({});
const currentEditingRow = ref(null);
const selectedRows = ref([]);  // 用于存储被选中的行的数据
const route = useRoute();
const realTableName = ref("");
const tableName = ref("");
const columns = ref([]);
const tableData = ref([]);
const searchTerm = ref("");
const currentPage4 = ref(1);
const pageSize = ref(5);
const totalItems = ref(0);
const selectedColumns = ref([]);
const isColumnSelectorVisible = ref(false);
const isAddDialogVisible = ref(false);
const formData = reactive({});
const tables = ref([]);
const activeTableName = ref("");
const multipleTable = ref(null);
const tableNames = ref(["t_bq_t", "t_czjl_t", "t_dj_t", "t_dxjg_t", "t_dxmb_t", "t_dxqm_t", "t_fwlx_t", "t_gsxx_t", "t_hmd_t", "t_hshdlx_t",
  "t_hslc_t", "t_hsmblx_t", "t_hsmb_t", "t_hstzjg_t", "t_jglx_t", "t_khzl_t", "t_log_t", "t_qjsz_t", "t_rwjgjf_t", "t_rwmx_t", "t_rw_t", "t_xtcs_t",
  "t_xtyhsc_t", "t_xtyhxx_t", "t_yh_t", "t_ywlc_t", "t_yxbqlx_t", "t_zsfl_t", "t_zs_t"]);
// 监听路由变化

const fetchTableColumns = async () => {
  try {

    await request.get(`/tables/${tableName.value}/columns`).then(res => {
      console.log(res);
      columns.value = res.data;
    });


    // const response = await axios.get(`http://localhost:9000/tables/${tableName.value}/columns`);
    // console.log(response.data); // 查看后端返回的列数据
    // columns.value = response.data;
  } catch (error) {
    console.error("Error fetching table columns", error);
  }
};

const fetchTableData = async () => {
  try {


    await request.get(`/tables/${tableName.value}`).then(res => {
      console.log(res);
      tableData.value = res.data;
    });

    // const response = await axios.get(`http://localhost:9000/tables/${tableName.value}`);
    // tableData.value = response.data;
  } catch (error) {
    console.error("Error fetching table data", error);
  }
};

watch(() => route.params.tableName, async (newTableName) => {
  tableName.value = newTableName;
  await fetchTableColumns();
  await fetchTableData();
  await fetchTables();  // 添加这行代码
}, { immediate: true });

// Methods
const fetchTables = async () => {
  try {
    // const response = await request.get(`/tables/table_labels`);

    await request.get("/tables/table_labels").then(res => {
      //
      // console.log(res.data)
      tables.value = res.data;
      const matchedTable = tables.value.find(t => t.table_name === tableName.value);
      if (matchedTable) {
        realTableName.value = matchedTable.label;
      }
    });
  } catch (error) {
    console.error("Error fetching tables:", error);
  }


  //
  // tables.value = response.data; // 假设 response.data 就是您需要的数据

};

onMounted(() => {
  fetchTables();
  // 你可以在这里调用其他需要在组件挂载时执行的函数
});

const clearFormData = () => {
  for (const prop in formData) {
    delete formData[prop];
  }
};

const handleAdd = () => {
  isAddDialogVisible.value = true;
  clearFormData();
};

const submitFormData = async () => {
  try {
    // 预处理 formData 中的 datetime 字段，将其转换为数据库可以接受的格式
    for (const key in formData) {
      if (formData.hasOwnProperty(key) && formData[key] instanceof Date) {
        formData[key] = formData[key].toISOString().slice(0, 19).replace('T', ' ');
      }
    }

    await request.post(`/tables/${tableName.value}/insert`, formData)
            .then(res => {
              ElMessage.success("添加成功");
            });

    // 之后刷新表格数据
    await fetchTableData();

    // 关闭模态框
    isAddDialogVisible.value = false;
  } catch (error) {
    console.error("Error submitting form data", error);
    // 显示详细的错误信息
    if (error.response && error.response.data) {
      ElMessage.error("系统内部异常: " + error.response.data);
    } else {
      ElMessage.error("系统内部异常: " + error.message);
    }
  }
};



const handleSearch = async () => {
  try {
    const columnsParam = selectedColumns.value.join(",");


    await request.get(`/tables/${tableName.value}/search`, {
      params: {
        searchTerm: searchTerm.value,
        columns: columnsParam
      }
    }).then(res => {
      console.log(res);
      tableData.value = res.data;
    });


    // const response = await axios.get(`http://localhost:9000/tables/${tableName.value}/search`, {
    //   params: {
    //     searchTerm: searchTerm.value,
    //     columns: columnsParam
    //   }
    // });
    // tableData.value = response.data;
  } catch (error) {
    console.error("Error searching table data", error);
  }
};

const handleReset = async () => {
  searchTerm.value = "";
  await fetchTableData();
};

const resetEditFormData = () => {
  editFormData.value = {}; // 根据您的实际初始状态来重置
};


const handleSelectionChange = (selected) => {
  resetEditFormData(); // 先重置
  console.log("Received rowData:", editFormData);
  currentEditingRow.value = editFormData;
  selectedRows.value = selected;
};

const deleteSelectedRows = async () => {
  if (!selectedRows.value.length) {
    alert("请先选择要删除的行！");
    return;
  }

  try {
    // 我假设你的后端接受一个ID数组来删除行
    const idsToDelete = selectedRows.value.map(row => row.F_ID);

    // 调用后端API
    // await axios.post(`http://localhost:9000/tables/${tableName.value}/delete`, idsToDelete);

    await request.post(`/tables/${tableName.value}/delete`, idsToDelete).then(res => {
      ElMessage.success("删除成功");
    });


    // 从前端表格数据中移除被删除的行
    tableData.value = tableData.value.filter(row => !idsToDelete.includes(row.F_ID));

    // 清空选中的行
    selectedRows.value = [];

  } catch (error) {
    console.error("Error deleting rows", error);
  }
};

const uniqueCols = computed(() => {
  const seen = new Set();
  return columns.value.filter(column => {
    const duplicateCheck = `${column.name}${column.label}${column.type}`;
    if (!seen.has(duplicateCheck)) {
      seen.add(duplicateCheck);
      return true;
    }
    return false;
  });
});


const submitEditData = async () => {
  if (!currentEditingRow.value || !currentEditingRow.value.F_ID) {
    console.error("currentEditingRow is not properly set!");
    return;
  }

  try {
    const dataToSend = prepareDataForUpdate(editFormData);

    await request.put(`/tables/${tableName.value}/${currentEditingRow.value.F_ID}`, dataToSend)
            .then(res => {
              ElMessage.success("更新成功");
            });

    const index = tableData.value.findIndex(item => item.F_ID === currentEditingRow.value.F_ID);
    if (index !== -1) {
      tableData.value.splice(index, 1, { ...editFormData });
    }
    isEditDialogVisible.value = false;
  } catch (error) {
    console.error("Error updating row:", error);
  }
};


const dateArrayFields = ["F_CJSJ", "F_GXSJ", "F_CZSJ", "F_DXTJSJ", "F_DXFSSJ"];  // 添加所有已知的日期时间数组字段名

const convertArrayToDateStr = (arr) => {
  if (Array.isArray(arr) && arr.length === 6) {
    return `${arr[0]}-${arr[1]}-${arr[2]} ${arr[3]}:${arr[4]}:${arr[5]}`;
  }
  return arr;
};

const convertISOToDateTime = (isoString) => {
  if (!isoString) return '';
  const date = new Date(isoString);
  const year = date.getFullYear();
  const month = (`0${date.getMonth() + 1}`).slice(-2);
  const day = (`0${date.getDate()}`).slice(-2);
  const hours = (`0${date.getHours()}`).slice(-2);
  const minutes = (`0${date.getMinutes()}`).slice(-2);
  const seconds = (`0${date.getSeconds()}`).slice(-2);
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const prepareDataForUpdate = (data) => {
  let preparedData = { ...data };

  for (const key in preparedData) {
    if (dateArrayFields.includes(key) && typeof preparedData[key] === 'string') {
      preparedData[key] = convertISOToDateTime(preparedData[key]);
    }
  }

  delete preparedData.F_ID;
  delete preparedData.value;

  return preparedData;
};


const toggleColumnSelector = () => {
  if (!isColumnSelectorVisible.value) {
    selectedColumns.value = [];
  }
  isColumnSelectorVisible.value = !isColumnSelectorVisible.value;
};

//图片
const beforeImageUpload = (file) => {
  const isJPGorPNG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 0.5;

  if (!isJPGorPNG) {
    ElMessage.error("上传图片只能是 JPG/PNG 格式!");
  }
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过 500KB!");
  }
  return isJPGorPNG && isLt2M;
};

const handleImageSuccess = (response, file) => {
  // 你可以在此处处理上传成功后的操作
  // 例如将返回的图片地址保存到formData中
  formData[column.name] = response.url;
};

const submitImage = () => {
  // 如果你想手动触发上传，可以在这里处理
};

const filteredColumns = computed(() => {
  return uniqueCols.value.filter(column => column.name !== "F_ID");
});

//添加
const handleRowClick = (row) => {
  const rowIndex = selectedRows.value.findIndex(item => item.id === row.id);
  if (rowIndex !== -1) {
    // 如果行已经被选中，则取消选择
    selectedRows.value.splice(rowIndex, 1);
  } else {
    // 否则添加到选中行列表中
    selectedRows.value.push(row);
  }
};

const openEditDialog = () => {
  if (selectedRows.value.length !== 1) {
    alert("请只选择一条数据进行编辑！");
    return;
  }

  // 更新currentEditingRow
  currentEditingRow.value = selectedRows.value[0];

  console.log("Editing:", currentEditingRow.value);
  // 使用Object.assign或其他方法来初始化编辑表单的数据
  Object.assign(editFormData, selectedRows.value[0]);

  isEditDialogVisible.value = true;
};


</script>


<style scoped>
.column-selector {
    max-height: 200px;
    overflow-y: auto;
}

.table-title {
    font-size: 24px;
    color: darkblue;
}

.operations {
    margin-bottom: 20px;
}

.navbar ul {
    flex-wrap: wrap; /* 添加换行行为 */
    display: flex; /* 应用 flex 布局 */
    list-style-type: none; /* 移除默认的列表符号 */
    padding: 0; /* 移除默认的内边距 */
}

.navbar ul li {
    margin: 10px; /* 在列表项之间添加一些间距 */
}

/* 可以添加更多的样式来调整链接的外观 */
.navbar ul li a {
    font-size: 18px; /* 增大字体大小 */
    text-decoration: none; /* 移除链接下划线 */
    color: #7ab8d6; /* 设置链接颜色 */
}

.navbar ul li a:hover {
    color: #0000ff; /* 鼠标悬停时的颜色，这里设置为蓝色 */
}
</style>

